<template>
  <el-form :model="user" :rules="userRules" ref="userRef" label-width="80px">
    <el-form-item label="姓名" prop="real_name">
      <el-input v-model.trim="user.real_name" clearable />
    </el-form-item>
    <el-form-item label="性别">
      <el-select v-model="user.gender" placeholder="请选择性别" clearable>
        <el-option
          v-for="item in genders"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="手机" prop="telephone">
      <el-input v-model.trim="user.telephone" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateUser } from "@/api/user";
export default {
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          id: undefined,
          real_name: "",
          gender: "",
          telephone: ""
        };
      }
    }
  },
  data(){
    return {
      userRules: {
        real_name: [
          { required: true, message: "请输入用户姓名", trigger: "blur" },
        ],
        telephone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
      },
      genders: [
        {
          value: "男",
          label: "男"
        },
        {
          value: "女",
          label: "女"
        }
      ]
    }
  },
  methods: {
    submit() {
      const userInfo = {
        id: this.user.id,
        real_name: this.user.real_name,
        gender: this.user.gender,
        telephone: this.user.telephone
      };
      console.log(userInfo);
      
      updateUser(userInfo)
        .then(res => {
          if (!res) {
            this.$message.error("用户信息修改失败");
          } else {
            this.$message({
              message: "用户信息修改成功",
              type: "success",
              duration: 5 * 1000
            });
          }
        })
        .catch(error => {
          console.log(error);
          this.$message.error("用户信息修改失败!!");
        });
    }
  },

};
</script>

<style lang='scss' scoped>
.el-input,
.el-select {
  width: 50%;
}
</style>